package com.example.demo.controller;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.example.demo.custom.AjaxResult;
import com.example.demo.entity.TwoCompany;
import com.example.demo.entity.TwoCompany2;
import com.example.demo.form.TwoCompanyForm2;
import com.example.demo.service.TwoCompany2Service;
import com.example.demo.service.TwoCompanyService;

@RestController
@RequestMapping(value = "/TwoCompany2")
public class TwoCompany2Controller {
	@Autowired
	private TwoCompanyService service1;
	@Autowired
	private TwoCompany2Service service2;
	
	private DateFormat dateFormat1 = new SimpleDateFormat("yyyy-MM-dd");
	
	
	@RequestMapping(value = "/save")
	private Object save(TwoCompanyForm2 Form) throws ParseException {
		Integer twoid1=Form.getId();
		Date d=new Date();
		Date d1=dateFormat1.parse("1999-01-01");
		TwoCompany two=new TwoCompany();
		TwoCompany Two=new TwoCompany();
		TwoCompany2 two2=new TwoCompany2();
		TwoCompany2 Two2=new TwoCompany2();
		if(twoid1==null) {
			Two.setName(Form.getName());
			two=service1.save(Two);
		}else {
			two=service1.findById(twoid1);
			two.setName(Form.getName());
			service1.save(two);
			List<TwoCompany2> list = service2.findByTwoCompany(two);
			for(TwoCompany2 twoCompany2 : list ) {
				if(d1.compareTo(twoCompany2.getBeginDate())==-1) {
					d1=twoCompany2.getBeginDate();
					Two2=twoCompany2;
				}
			}
			Two2.setEndDate(d);
			service2.save(Two2);
		}
		BeanUtils.copyProperties(Form, two2, "id","name");
		two2.setTwoCompany(two);
		two2.setBeginDate(d);
		service2.save(two2);
		return new AjaxResult("数据保存成功");
	}
	
	@RequestMapping(value = "/list")
	private Object list() {
		return new AjaxResult(service1.findAll());
	}
	
	@RequestMapping(value = "/findbyId")
	private Object findbyId(Integer id) throws ParseException{
		List<TwoCompany2> list=service2.findByTwoCompanyId(id);
		DateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd");
		Date d=dateFormat.parse("1999-01-01");
		TwoCompany2 two=new TwoCompany2();
		for(TwoCompany2 y:list) {
			if(d.compareTo(y.getBeginDate())==-1) {
				d=y.getBeginDate();
				two=y;
			}
		}
		return new AjaxResult(two);
	}
}
